package edu.hit.pact.pgse.crawler.web;

import java.io.Serializable;
import java.net.*;
import java.util.concurrent.atomic.AtomicInteger;

import edu.hit.pact.pgse.bean.RunnableTask;

public class UrlUnit implements Serializable, Comparable<UrlUnit>{

	private static final long serialVersionUID = -5245230137954316083L;
	
//	private final String taskPieceIdWithTime;
//	
//	private final URL url;	//url
//	
//	private final String refereUrl;
	
	private final String url;
	private final int currDepth; 	// current depth
	private AtomicInteger backlinks;

	public UrlUnit(String url, int currDepth) {
		super();
		this.url = url;
		this.currDepth = currDepth;
		this.backlinks = new AtomicInteger(0);
	}
	
	public int getBacklinks() {
		return backlinks.get();
	}

	public void incrementBackLinks(){
		backlinks.incrementAndGet();
	}
	
	public void incrementBackLinksByNum(int num){
		backlinks.set(backlinks.intValue()+num);
	}
	
	/**
	 * @return the url
	 * @throws MalformedURLException 
	 */
	public URL getUrl(){
		try {
			return new URL(url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String getLink() {
		return url;
	}

	public String getHostName(){
		try {
			return new URL(url).getHost();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String getFullHostName(){
		URL urlLink;
		try {
			urlLink = new URL(url);
			if (urlLink.getPort() == -1) {
				return urlLink.getHost();
			} else {
				return urlLink.getHost() + ":" + urlLink.getPort();
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public int getCurrDepth() {
		return currDepth;
	}
	
	public String getProtocol(){
		try {
			return new URL(url).getProtocol();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String getPath(){
		try {
			String path = new URL(url).getPath();
			if(null == path || path.equals("")){
				return "/";
			}else{
				return path;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public int compareTo(UrlUnit simpleUrlUnit) {//big item is in front of small one
		
		if (backlinks.get() == simpleUrlUnit.getBacklinks()){
			return 0;
		} else {
			return backlinks.get() > simpleUrlUnit.getBacklinks() ? -1 : 1;
		}
	}
}

